package com.zjl.service.impl;

import com.zjl.mapper.DeptMapper;
import com.zjl.mapper.EmpMapper;
import com.zjl.pojo.Dept;
import com.zjl.pojo.DeptLog;
import com.zjl.service.DeptLogService;
import com.zjl.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName DeptServiceImpl
 * @Description 部门表逻辑实现层
 * @Author ZJL
 * @Date 2023/10/26 18:25
 * @Version 1.0
 **/
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptLogService deptLogService;

    @Override
    public List<Dept> list() {
        /**
         * 查询部门列表查询
         */
        List<Dept> deptList = deptMapper.query();
        return deptList;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)  //当前方法添加了事务管理
    public Integer delete(Integer id) throws Exception {
        try {
            //根据部门id删除部门信息
            Integer result = deptMapper.deleteById(id);

            //模拟：异常
//            if(true){
//                throw new Exception("出现异常了~~~");
//            }

            //删除部门下的所有员工信息
            empMapper.deleteByDeptId(id);
            return result;

        } finally {
            //不论是否有异常，最终都要执行的代码：记录日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此时解散的是"+id+"号部门");
            //调用其他业务类中的方法
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public Integer add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.insert(dept);
    }

    @Override
    public Dept getById(Integer id) {
        Dept dept = deptMapper.getDeptById(id);
        return dept;
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
